
package dal;
import entity.User;
import java.io.File;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class userDal {

    public void saveUsers(List<User> users){
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = factory.newDocumentBuilder();
            Document doc = docBuilder.newDocument();
            Node root = doc.createElement("UserStore");
            doc.appendChild(root);
            for (int i = 0; i < users.size(); i++) {
                Node user = doc.createElement("acc");

                Node username = doc.createElement("name");
                username.setTextContent(users.get(i).getUsername());
                user.appendChild(username);

                Node password = doc.createElement("pass");
                password.setTextContent(users.get(i).getPassword());
                user.appendChild(password);

                root.appendChild(user);
            }

            TransformerFactory tranFac = TransformerFactory.newInstance();
            Transformer transformer = tranFac.newTransformer();
            Source source = new DOMSource(doc);
            Result result = new StreamResult(new File("account_1.xml"));
            transformer.transform(source, result);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public List<User> loadUser(){
        List<User> users = new LinkedList<User>();
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = factory.newDocumentBuilder();
            Document doc = docBuilder.parse(new File("account_1.xml"));
            NodeList userNodes = doc.getElementsByTagName("acc");

            for (int i = 0; i < userNodes.getLength(); i++) {
                Node user = userNodes.item(i);
                //Ep kieu sang Element de getByTag
                String name = ((Element)user).getElementsByTagName("name").item(0).getTextContent();
                String pass = ((Element)user).getElementsByTagName("pass").item(0).getTextContent();
                User u  = new User(name, pass);
                users.add(u);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return users;
    }
}
